package cn.itcast.bos.web.action.system;

import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.UserService;
import cn.itcast.bos.utils.BaseAction;
import com.opensymphony.xwork2.ActionContext;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.List;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("protoType")
public class UserAction extends BaseAction<User> {
    @Autowired
    private UserService userService;

    @Action(value="user_login",results = {@Result(name="success",type = "redirect",location = "index.html"),
                                            @Result(name="login",type="redirect",location = "login.html")})
    public String Login(){
        //基于shiro实现登陆
        Subject subject = SecurityUtils.getSubject();
        //用户名和密码信息
        AuthenticationToken token = new UsernamePasswordToken(model.getUsername(),model.getPassword());
        //完成登陆
        try {
            //登陆成功
            subject.login(token);
            //将信息保存到session中

            return SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            //登陆失败
            return "login";
        }

    }
    //退出登录的方法
    @Action(value = "user_loginout",results = {@Result(name="success",type = "redirect",location = "login.html")})
    public String loginout(){
        Subject subject=SecurityUtils.getSubject();
        subject.logout();

        return SUCCESS;
    }
    //查找所有用户的方法
    @Action(value = "user_findAll",results = {@Result(name="success",type = "json")})
    public String findAllUser(){
        List<User> users = userService.findAll();
        ActionContext.getContext().getValueStack().push(users);
        return SUCCESS;
    }
    //保存用户的方法
    private String[] roleIds;

    public void setRoleIds(String[] roleIds) {
        this.roleIds = roleIds;
    }

    @Action(value = "user_save",results = {@Result(name="success",type = "redirect",location = "./pages/system/userlist.html")})
    public String saveUser(){
        userService.save(model,roleIds);
        return SUCCESS;
    }

}
